import requests
import json
import re
import os
import sys
from lxml import etree

cwd = os.getcwd()
sys.path.append(cwd)
print(cwd)

class ImageSo(object):
    url = 'https://image.so.com/j'
    save_dir = './so' # 文件保存的路径
    count = 0

    # 初始化
    def __init__(self, word):
        self.word = word
        self.dir_path = os.path.join(self.save_dir, word)
        self.params = {
            'q': word,
            'pd': '1',
            'src': 'srp',
            'pn': '60', # 数量
            'correct': word,
            'adstar': '0',
            'tab': 'all',
            'sid': '6252a4cf99bca96188ceb82841b56c57',
            'ras': '1',
            'cn': '0',
            'gn': '0',
            'kn': '50',
            'crn': '0',
            'bxn': '20',
            'ps': '0', # 开始
            'sn': '60', # 结束
        }
        self.headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Cookie': '__guid=15484592.1779259064897608400.1576717707421.6306; __huid=11AOUMb%2FnFdNlr5nhw1kr0pViBG7dtoHc%2BwfzWzVRHpiM%3D; QiHooGUID=7ACA75F41F363B572B663D5CB9D689EF.1576717701516; count=1; tracker=; HSPK=1263bf9e6cfbaf19731f8f3e1e1c4b3.1587863329.1; test_cookie_enable=null; gtHuid=1; opqopq=243883e82df690bbb7226bafbe71c4c4.1587866390',
            'Host': 'image.so.com',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'none',
            'Sec-Fetch-User': '?1',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36',
            # 'Referer': 'https://image.so.com/i?q=%s&src=srp'%word,
        }
        # 创建保存图片的文件夹
        self.folder_exist(self.dir_path)
        self.last_img_url = ''
        self.current_page = 0
    
    # 请求包含图片url的网页
    def parse(self):
        while True:
            self.params['ps'] = str(self.current_page*60)
            self.params['sn'] = str((self.current_page+1)*60)
            response = requests.get(url=self.url, headers=self.headers, params=self.params)
            response.encoding='utf8'
            # print(response.json())
            data = response.json()['list']
            if data:
                for img_info in data:
                    img_url = img_info['thumb']
                    # print(img_url)
                    self.download(img_url)
                print(self.current_page, len(data))
                self.current_page += 1
            else:
                break

    # 下载一张图片
    def download(self, img_url, img_type='jpg'):
        self.count += 1
        print('正在下载第%d张图片...'%self.count, img_url)
        response = requests.get(img_url)
        img_name = img_url.split('/')[-1]
        img_path = os.path.join(self.dir_path, img_name)
        with open(img_path, 'wb') as f:
            f.write(response.content)

    def folder_exist(self, dir_path):
        '''
        1. 作用:判断文件夹路径是否存在,不存在则创建
        2. 参数:dir_path:文件夹路径
        3. 返回值:None
        '''
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

if __name__ == '__main__':
    image = ImageSo('黑色牌照')
    image.parse()